﻿using System.Text.RegularExpressions;
using System.Windows.Forms;
using Me.Amon.POS.M;
using Me.Amon.Util;

namespace Me.Amon.POS.V
{
    public partial class WfPay : Form
    {
        private MSoHeader _SoHeader;
        private int _Paid;

        public WfPay()
        {
            InitializeComponent();
        }

        public void ShowPay(MSoHeader soHeader)
        {
            _SoHeader = soHeader;
            if (soHeader == null)
            {
                return;
            }

            TbNpay.Text = CharUtil.FormatPrice(soHeader.round_amount);
            _Paid = 0;
            TbNpay.Focus();
        }

        private void WfPay_Load(object sender, System.EventArgs e)
        {
            TbRpay.SelectAll();
        }

        private void WfPay_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                e.Handled = true;
                Close();
                return;
            }
            if (e.KeyCode != Keys.Enter)
            {
                return;
            }

            var text = TbRpay.Text.Trim();
            if (string.IsNullOrWhiteSpace(text))
            {
                LlErr.Text = "请输入实收金额！";
                return;
            }
            if (!Regex.IsMatch(text, "^\\d+([.]\\d{1,2})?$"))
            {
                LlErr.Text = "请输入有效的实收金额！";
                return;
            }

            _Paid += CharUtil.ParsePrice(text);
            if (_Paid < _SoHeader.round_amount)
            {
                TbRpay.Text = "";
                LlErr.Text = string.Format("已付：{0} 缺额：{1}", CharUtil.FormatPrice(_Paid), CharUtil.FormatPrice(_SoHeader.round_amount - _Paid));
                return;
            }

            _SoHeader.prepay_amount = _Paid;
            _SoHeader.change_amount = _SoHeader.prepay_amount - _SoHeader.round_amount;

            e.Handled = true;
            DialogResult = System.Windows.Forms.DialogResult.OK;
            Close();
        }
    }
}
